package com.hegaoye.mqhandler;

import com.hegaoye.base.RabbitmqConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * Created by lixin on 2019/6/29.
 */
@Slf4j
@Component
public class TestSender implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);

    }

    /**
     * 发送确认模式
     *
     * @param message
     */
    public void sendToConfirm(String message) {
        for (int i = 0; i < 100; i++) {
            rabbitTemplate.convertAndSend(RabbitmqConfig.Test_EXCHANGE_NAME, RabbitmqConfig.Test_QUEUE_NAME, message + i);
        }
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            log.info("success");
        } else {
            log.error("failed");
        }
    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        log.info("return--message:" + new String(message.getBody()) + ",replyCode:" + replyCode + ",replyText:" +
                replyText + ",exchange:" + exchange + ",routingKey:" + routingKey);
    }
}
